<?php
header("content-type:text/html;charset=utf-8");
echo '商品数据生成<br>';

function db_connect(string $dbname, string $user, string $pwd) {
    $dsn = 'mysql:dbname='.$dbname.';host=127.0.0.1';
    try {
        $db = new PDO($dsn, $user, $pwd);
    } catch (Exception $e) {
        echo 'Exception Message:'.$e->getMessage();
    }
    return $db;    
}

function table_insert(PDO $db, string $name, float $salary, int $number) {
    $sql = "INSERT INTO goods (`name`, `salary`, `number`) 
            VALUES ('".$name."', ".$salary.", ".$number.")";
    if ($db->exec($sql) == false) {
        echo 'Insert Failed:'.$db->errorCode().'<br>';
        return false;
    }
    return true;
}

function table_create(PDO $db, string $name) {
    $sql = "CREATE TABLE IF NOT EXISTS `goods` (
        `id` INT UNSIGNED AUTO_INCREMENT NOT NULL,
        `name` VARCHAR(64) NOT NULL,
        `salary` DECIMAL(8, 2) NOT NULL,
        `number` INT UNSIGNED NOT NULL,
        PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
    $db->exec($sql);
}

function table_delete(PDO $db, string $name) {
    $sql = "DROP TABLE {$name}";
    $db->exec($sql);
}

$db = db_connect('cart', 'root', '1234');
table_delete($db, 'goods');
table_create($db, 'goods');
table_insert($db, 'banana', 3, 20);
table_insert($db, 'pen', 20, 10);
table_insert($db, 'apple', 5, 50);
table_insert($db, 'iphone', 4999, 3);
table_insert($db, 'peisi', 3, 30);
$db = null;
echo '构建成功！'.'<br>';

?>